package org.gitos.cloud.comet.tcp;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;

import org.gitos.cloud.comet.logic.LogicLoop;
import org.gitos.cloud.comet.mq.PushManager;
import org.gitos.cloud.domain.comm.Constant;
import org.gitos.cloud.domain.mq.MqMsg;
import org.gitos.cloud.domain.tcp.Bucket;
import org.gitos.cloud.domain.tcp.DeviceId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

/**
 * Created by szc on 2015/12/5.
 * 消息派发
 */
@ChannelHandler.Sharable
@Component
public class DispatchBucketHandler extends ChannelInboundHandlerAdapter {
    private static final Logger log = LoggerFactory.getLogger(DispatchBucketHandler.class);
    private static final String routeKey = "default";
    @Autowired
    private LogicLoop loop;
    @Autowired
    private PushManager pushManager;
    @Value("${" + Constant.NODE_ID + "}")
    private String nodeId;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof Bucket)) {
            log.error("取得得数据非bucket");
            super.channelRead(ctx, msg);
            return;
        }
        Bucket bucket = (Bucket) msg;
        Attribute<DeviceId> attr = ctx.attr(Constant.DEVICE_ATTR_KEY);
        attr.set(((Bucket) msg).getDeviceId());
        log.info("取得bucket, content:{}", bucket.getContent());
        loop.pushJob(bucket);
        ReferenceCountUtil.release(msg);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {

        Attribute<DeviceId> attr = ctx.attr(Constant.DEVICE_ATTR_KEY);
        DeviceId deviceId = attr.get();
        if(deviceId==null){
            return;
        }
        MqMsg pushMsg=new MqMsg();
        Bucket bucket = new Bucket();
        bucket.setDeviceId(deviceId);
        pushMsg.setBucket(bucket);
        pushMsg.setChannelId(ctx.channel().id().asLongText());
        pushMsg.setNodeId(nodeId);
        pushMsg.setEvent(Constant.CMD_UP_DISCONNECT);
        pushManager.sendMsg(routeKey,pushMsg);
        super.channelUnregistered(ctx);
    }

}
